package com.stylefeng.guns.modular.system.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.common.constant.state.SpType;
import com.stylefeng.guns.core.model.Pager;
import com.stylefeng.guns.core.util.JwtTokenUtil;
import com.stylefeng.guns.modular.system.dao.OrgcategoryRoleMapper;
import com.stylefeng.guns.modular.system.model.OrgcategoryRole;
import com.stylefeng.guns.modular.system.model.SysPrivilege;
import com.stylefeng.guns.modular.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * <p>
 * 机构分类角色模板 服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2018-09-12
 */
@Service
public class OrgcategoryRoleServiceImpl extends ServiceImpl<OrgcategoryRoleMapper, OrgcategoryRole> implements IOrgcategoryRoleService {
    @Resource
    private OrgcategoryRoleMapper orgcategoryRoleMapper;
    @Autowired
    private IOrgcategoryFunctionService orgcategoryFunctionService;
    @Autowired
    private IOrgService orgService;
    @Autowired
    private IRoleCwService roleCwService;
    @Autowired
    private ISysPrivilegeService privilegeService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IOrgcategoryRoleFunctionService orgcategoryRoleFunctionService;

    /**
     * 新增机构分类角色
     * @author sasazaixian
     * @date 2018-10-04
     * @param orgcategoryRole 机构分类角色对象
     * @return
     */
    @Transactional
    public int insertOrgcategoryRole(OrgcategoryRole orgcategoryRole,String token)throws DataAccessException{
        if(orgcategoryRole==null || orgcategoryRole.getSocId()==null || orgcategoryRole.getSocId().trim().length()<1){
            throw new RuntimeException("参数不全！");
        }
        //检测同一个机构分类下角色名是否重复
        List list = orgcategoryRoleMapper.selectListOrgcategoryRoleForUpdate(orgcategoryRole);
        if(list!=null && list.size()>0){
            throw new RuntimeException("角色名称已经存在！");
        }

        /*********如果主键是UUID 可以启用以下方式 仅供参考*************/
        /*if(orgcategoryRole!=null && (orgcategoryRole.getSorId()==null || orgcategoryRole.getSorId().trim().length()<10)){
            orgcategoryRole.setSorId(IdWorker.get32UUID());
        }*/
        //初始化时间和创建人
        String subject = JwtTokenUtil.getClaimFromToken(token).getSubject();//用户ID
        orgcategoryRole.setCreateUser(subject);
        Date now = DateTime.now();
        orgcategoryRole.setCreateTime(now);

        int ret=this.orgcategoryRoleMapper.insertOrgcategoryRole(orgcategoryRole);
        //根据机构分类角色id ，同步机构分类角色到机构
        //addRoletoSubOrg(""+orgcategoryRole.getSorId(),token);
        return ret;
    }

    /**
     * 更新机构分类角色
     * @author sasazaixian
     * @date 2018-10-04
     * @param orgcategoryRole 机构分类角色对象
     * @return
     */
    @Transactional
    public int updateOrgcategoryRole(OrgcategoryRole orgcategoryRole,String token)throws DataAccessException{
        if(orgcategoryRole==null || orgcategoryRole.getSocId()==null || orgcategoryRole.getSocId().trim().length()<1){
            throw new RuntimeException("参数不全！");
        }
        //检测同一个机构分类下角色名是否重复
        List list = orgcategoryRoleMapper.selectListUpdateOrgcategoryRoleForUpdate(orgcategoryRole);
        if(list!=null && list.size()>0){
            throw new RuntimeException("角色名称已经存在！");
        }
        String subject = JwtTokenUtil.getClaimFromToken(token).getSubject();//用户ID
        orgcategoryRole.setUpdateUser(subject);
        Date now = DateTime.now();
        orgcategoryRole.setUpdateTime(now);
        this.orgcategoryRoleMapper.updateOrgcategoryRole(orgcategoryRole);

        //批量修改角色名
        /*RoleCw sysRole =new RoleCw();
        sysRole.setSrcTemId(orgcategoryRole.getSorId());
        sysRole.setSrSource("1");
        sysRole.setSrName(orgcategoryRole.getSorName().trim());
        //批量同步角色名
        roleCwService.updateBatchRoleCw(sysRole);*/
        return 0;
    }
    /**
     * 查询机构分类角色
     * @author sasazaixian
     * @date 2018-10-04
     * @param orgcategoryRole 机构分类角色对象
     * @return
     */
    public List<OrgcategoryRole> listOrgcategoryRole(OrgcategoryRole orgcategoryRole)throws DataAccessException{
        if(orgcategoryRole==null || orgcategoryRole.getSocId()==null || orgcategoryRole.getSocId().trim().length()<1){
            throw new RuntimeException("机构分类不能为空！");
        }
        return  this.orgcategoryRoleMapper.selectListOrgcategoryRole(orgcategoryRole);
    }
    /**
     * 分页查询机构分类角色
     * @author sasazaixian
     * @date 2018-10-04
     * @param pager 机构分类角色对象
     * @return
     */
    public Map pageListOrgcategoryRole(Pager pager)throws DataAccessException{
        OrgcategoryRole orgcategoryRole=(OrgcategoryRole)pager.getObj();
        if(orgcategoryRole==null || orgcategoryRole.getSocId()==null || orgcategoryRole.getSocId().trim().length()<1){
            throw new RuntimeException("机构分类不能为空！");
        }
        Page page=new Page(pager.getPageNumber(),pager.getPageSize());
        page.setRecords(orgcategoryRoleMapper.selectListOrgcategoryRole(page,orgcategoryRole));
        List<OrgcategoryRole> list = page.getRecords();
        Map mapDate = new HashMap();
        mapDate.put("rows", list);
        mapDate.put("total", page.getTotal());
        mapDate.put("page", page.getCurrent());
        mapDate.put("pageCount", page.getPages());
        return mapDate;

    }
    /**
     * 根据id获取机构分类角色
     * @author sasazaixian
     * @date 2018-10-04
     * @param id 机构分类角色id
     * @return
     */
    public OrgcategoryRole findById(String id)throws DataAccessException{
        return  orgcategoryRoleMapper.findOrgcategoryRoleById(id);
    }
    /**
     * 删除机构分类角色
     * @author sasazaixian
     * @date 2018-10-04
     * @param ids 机构分类角色id数组
     * @return
     * */
    @Transactional
    public int delOrgcategoryRole(String[] ids) throws DataAccessException {
        for(String id:ids){
            //删除机构分类下机构对应的角色和功能
            this.delRoletoSubOrg(id);
        }
        orgcategoryRoleMapper.deleteBatchOrgcategoryRole(ids);
        return 0;
    }
    /**
     * 删除机构分类下同步的角色和功能
     * @throws Exception
     */
    public void delRoletoSubOrg(String orgCateRoleId) throws DataAccessException{
        //删除机构分类角色授权
        SysPrivilege privilege=new SysPrivilege();
        privilege.setSpType(SpType.ROLE.getCode());
        privilege.setSpTypeId(orgCateRoleId);//角色
        privilegeService.deleteSysPrivilege(privilege);
        //获取组织分类
        //通过机构分类角色id获取机构分类
        /*OrgcategoryRole sorgRole=this.orgcategoryRoleMapper.findOrgcategoryRoleById(orgCateRoleId);
        RoleCw selSysRole = new RoleCw();
        selSysRole.setSrcTemId(Integer.parseInt(orgCateRoleId));
        selSysRole.setSrSource("1");
        List<RoleCw> roleCwList=roleCwService.selectListRoleCw(selSysRole);
        //删除角色功能
        for(RoleCw role:roleCwList){

            SysPrivilege privilege=new SysPrivilege();
            privilege.setSpType(SpType.ROLE.getCode());
            privilege.setSpTypeId(role.getSrId());//角色
            privilegeService.deleteSysPrivilege(privilege);

        }
        //批量删除角色
        roleCwService.deleteRoleCw(selSysRole);
        //删除系统分类角色功能
        OrgcategoryRoleFunction orgcategoryRoleFunction=new OrgcategoryRoleFunction();
        orgcategoryRoleFunction.setSorId(Integer.parseInt(orgCateRoleId));
        orgcategoryRoleFunctionService.deleteOrgcategoryRoleFunction(orgcategoryRoleFunction);
        */
    }
    /**
     * 将机构分类角色同步到机构角色中 此方法已经作废
     * @param orgCateRoleId
     * @throws Exception
     */
    /*public void addRoletoSubOrg(String orgCateRoleId,String token)throws DataAccessException{
        //通过机构分类角色id获取机构分类
        OrgcategoryRole sorgRole=this.orgcategoryRoleMapper.findOrgcategoryRoleById(orgCateRoleId);
        //获取机构分类下所有组织
        Org sysOrg=new Org();
        sysOrg.setSoCate(sorgRole.getSocId());
        List<Org> orgList=orgService.selectListOrg(sysOrg);
        for(Org tempOrg:orgList){
            RoleCw selSysRole = new RoleCw();
            selSysRole.setSoId(tempOrg.getSoId());
            selSysRole.setSrcTemId(sorgRole.getSorId());
            selSysRole.setSrSource("1");//0 手动增加 1：自动导入
            List<RoleCw>listSysRole =roleCwService.selectListRoleCwForUpdate(selSysRole);
            if(listSysRole==null || listSysRole.size()==0){
                //插入角色
                RoleCw orgRole = new RoleCw();
                orgRole.setSoId(tempOrg.getSoId());
                orgRole.setSrSort(999);
                orgRole.setSrSource("1");//0 手动增加 1：自动导入
                orgRole.setSrcTemId(sorgRole.getSorId());
                orgRole.setSrName(sorgRole.getSorName());
                orgRole.setCreateTime(DateTime.now());
                orgRole.setCreateUser(JwtTokenUtil.getClaimFromToken(token).getSubject());
                roleCwService.insertRoleCw(orgRole);
            }
        }
    }*/
}
